//
// Created by 李传智 on 2018/4/12.
//

#include "IDecode.h"
#include "Logger.h"

void IDecode::update(VideoData data) {
    if (codecType != data.codecType) {
        return;
    }
    while (!isExist) {
        pktMutex.lock();
        if (pkts.size() <= maxPackets) {
            pkts.push_back(data);
            pktMutex.unlock();
            break;
        }
        pktMutex.unlock();
        sleep(1);
    }
}

void IDecode::main() {
    while (!isExist) {
        pktMutex.lock();

        // 判断音视频同步
        if (!isAudio && syncPts > 0) {
            // 只做视频处理，同步音频的pts
            if (syncPts < pts) {
                pktMutex.unlock();
                sleep(1);
                continue;
            }
        }

        if (pkts.empty()) {
            pktMutex.unlock();
            sleep(1);
            continue;
        }
        VideoData packet = pkts.front();
        pkts.pop_front();
        // 发送数据到解码线程
        if (this->sendPacket(packet)) {
            // 一个数据包可能解码多个结果
            while (!isExist) {
                VideoData frame = this->receiveFrame();
                if (frame.size <= 0) {
                    break;
                }
                pts = frame.pts;
                //LOG_I("receive frame size = %d", frame.size);
                // 发送数据给观察者
                this->notify(frame);
            }
        }
        packet.free();
        pktMutex.unlock();
    }
}

void IDecode::clear() {
    pktMutex.lock();
    while (!pkts.empty()) {
        pkts.front().free();
        pkts.pop_front();
    }
    syncPts = 0;
    pts = 0;
    pktMutex.unlock();
}